# coding:UTF-8
'''
Created on 2015年3月28日

@author: Jeffrey

内容生产模块
'''

import traceback
import json

from django.http.response import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from youaiwang.settings import BASE_DIR
from django.template.context import RequestContext
from youaiwang.views import updateNewMessage
from lib.utils import do_logging, login
from account.views import loginbyemail
from account.models import User as UserModel, Message as MessageModel
from forum.models import (Sharing as SharingModel,
                          Comment as CommentModel,
                          Reply as ReplyModel,
                          Praise as PraiseModel,
                          Collection as CollectionModel,
                          City as CityModel,)
from account.UEditor_views import judgeAction
from django.views.decorators.csrf import csrf_exempt



def add_sharing(request):
    """
    添加分享
    :param request:
    :return:
    """
    obj = {}
    if request.method == 'GET':
        if request.session.get('webStatus', '') == 'HasLogin':
            obj['message_count'] = updateNewMessage(request, obj)
            obj['session'] = request.session
            obj['cities'] = CityModel.objects.filter(status=1)
            return render_to_response('forum/add_article.html', {'obj': obj}, context_instance=RequestContext(request))
        else:
            return render_to_response('account/login.html', {'obj': obj}, context_instance=RequestContext(request))
    else:
        if request.method == "POST":
            if request.session.get('webStatus', '') == 'HasLogin':
                userId = request.session.get('userId')
                article = SharingModel()

                try:
                    user = UserModel.objects.get(id=userId)
                    article.author = user
                    article.title = request.POST.get('article_hd_input', '')
                    article.preview = request.POST.get('article_pre_input', '')
                    article.tags = request.POST.get('article_tags_input', '')
                    article.content = request.POST.get('content_text', '')
                    article.save()
                except:
                    raise
                return HttpResponseRedirect('/account/profile/' + str(article.author_id) + '/')
            else:
                return render_to_response('account/login.html', {'obj': obj}, context_instance=RequestContext(request))

@login
def add_comment_in_sharing(request, articleId):
    if request.method == 'POST':
        if request.session.get('webStatus', '') == 'HasLogin':
            try:
                userId = request.session.get('userId', '')
                article = SharingModel.objects.get(id=articleId)
                user = UserModel.objects.get(id=userId)
                comment = CommentModel()
                comment.article = article
                comment.reviewer = user
                comment.content = request.POST.get('comment_textarea', '')
                comment.save()
                msg = MessageModel()
                msg.fromPer = user
                msg.toPer = article.author
                msg.type = 2 # 评论消息类型
                msg.originUser = article.author
                msg.originContent = article.title[:10]
                msg.content = comment.content
                msg.originUrl = "/forum/sharing/" + articleId + "/?id=" + "#comment_div_" + str(comment.id)
                msg.save()
                msg.message_id = msg.id
                msg.save()
                return HttpResponseRedirect(msg.originUrl)
            except:
                raise

def add_praise_in_sharing(request, articleId):
    """
    匿名用户其实就是管理员，其userId=1
    """
    if request.method == 'GET':
        try:
            user = UserModel.objects.get(id=1)
            article = SharingModel.objects.get(id=articleId, status=True)
            praise = PraiseModel()
            praise.source = article.id
            praise.sourceType = 1 # 配置参数中的长文章类型,
            praise.fromUser = user
            praise.save()
            msg = MessageModel()
            msg.fromPer = user
            msg.toPer = article.author
            msg.type = 1
            msg.originUser = article.author
            msg.originContent = article.title[:10]
            msg.content = ""
            msg.originUrl = "/forum/" + articleId + "/"
            msg.save()

            return HttpResponse(PraiseModel.objects.filter(status=True, sourceType=1, source=str(article.id)).values('id').count())
        except Exception as e:
            do_logging('error', e, traceback.format_exc())
            raise

def add_reply_in_sharing(request, articleId, commentId, receiverId):
    '''
    唯有POST请求能处理
    '''
    if request.method == "POST":
        if request.session.get('webStatus', ''):
            try:
                userId = request.session.get('userId', '')
                comment = CommentModel.objects.get(id=commentId, status=True)
                article = SharingModel.objects.get(id=articleId)
                user = UserModel.objects.get(id=userId, status=True)
                reply = ReplyModel()
                reply.comment = comment
                reply.firstPer = user
                receiver = UserModel.objects.get(id=receiverId, status=True)
                reply.secondPer = receiver
                reply.content = request.POST.get('reply_input_' + str(comment.id), '')
                reply.save()
                msg = MessageModel()
                msg.fromPer = user
                msg.toPer = receiver
                msg.type = 3 # 回复消息类型
                msg.originUser = article.author
                msg.originContent = comment.content[:10]
                msg.content = reply.content
                msg.originUrl = "/forum/sharing/" + articleId + "/?id=" + "#reply_contentdiv_" + str(reply.id)
                msg.save()
                return HttpResponseRedirect(msg.originUrl)
            except:
                raise

def add_collection_in_sharing(request, articleId):
    if request.method == 'GET':
        if request.session.get('webStatus', '') == 'HasLogin':
            try:
                userId = request.session.get('userId', 0)
                user = UserModel.objects.get(id=userId)
                article = SharingModel.objects.get(id=articleId)
                collection = CollectionModel()
                collection.source = article.id
                collection.sourceType = 1 # 配置参数中的长文章类型
                # collection.article.article_title[:10]
                collection.url = "/forum/sharing/" + articleId + "/"
                collection.content = article.title
                collection.save()
                collection.collectors.add(user)
                return HttpResponse(CollectionModel.objects.filter(status=True, sourceType=1, source=article.id).values('id').count())
            except Exception as e:
                do_logging('error', e, traceback.format_exc())
                raise
                # return HttpResponse("数据库操作出错！")
        else:
            return HttpResponse('Not Login!')
    else:
        return HttpResponse("Not GET!")

def get_article(request, articleId):
    obj = {}
    # GET
    if request.method == "GET":
        obj['message_count'] = updateNewMessage(request, obj)
        obj['session'] = request.session
        # 寻找文章评论列表
        try:
            article = SharingModel.objects.get(id=articleId, status=True)
            article.allScanCount += 1
            article.save(update_fields=['allScanCount'])
            commentList = CommentModel.objects.filter(article=article, status=True)
            praise = PraiseModel.objects.filter(status=True, sourceType=1, source=str(article.id)).values('id')
            collection = CollectionModel.objects.filter(status=True, sourceType=1, source=article.id).values('id')

            obj.update({
                'article': article,  # 用模板过滤器safe输出content
                'commentList': commentList,
                'praiseCount': len(praise) if praise else 0,
                'collectionCount': len(collection) if collection else 0,
            })
            return render_to_response('forum/index.html', {'obj': obj}, context_instance=RequestContext(request))
        except Exception as e:
            do_logging('error',e , traceback.format_exc())

    # POST
    elif request.method == "POST":
        if request.session.get('webStatus', '') != 'HasLogin':
            # 登录
            loginbyemail(request)
            return HttpResponseRedirect('/forum/' + articleId + '/')

def selectedModule(module):
    if module == "travelfootmark":
        module = "旅行足迹"
    if module == "present":
        module = "礼物"
    if module == "thinking":
        module = "心声"
    return module

def add_question(request):
    obj = {}
    if request.method == 'GET':
        if request.session.get('webStatus', '') == 'HasLogin':
            message_count = 5
            obj['message_count'] = message_count
            obj['session'] = request.session
            obj['cities'] = CityModel.objects.filter(status=1)
            return render_to_response('forum/add_article.html', {'obj': obj}, context_instance=RequestContext(request))
        else:
            return render_to_response('account/login.html', {'obj': obj}, context_instance=RequestContext(request))
    else:
        if request.method == "POST":
            if request.session.get('webStatus', '') == 'HasLogin':
                userId = request.session.get('userId', 0)
                article = SharingModel()
                try:
                    user = UserModel.objects.get(id=userId)
                    article.author = user
                    article.save()
                    article.title= request.POST.get('article_hd_input', '')
                    article.preview = request.POST.get('article_pre_input', '')
                    article.tags = request.POST.get('article_tags_input', '')
                    article.content = request.POST.get('content_text', '')
                    article.save()
                except Exception as e:
                    do_logging('error', e, traceback.format_exc())
                return HttpResponseRedirect('/account/profile/' + str(article.author__id) + '/')
            else:
                return loginbyemail(request)

@csrf_exempt
def handle_upload(request):
    return judgeAction(request)

def get_article_list(obj, user):
    # 渲染文章列表
    sharingList = SharingModel.objects.filter(article_author=user, article_module=1, status=1)
    obj['sharingList'] = sharingList
    pictureList = SharingModel.objects.filter(article_author=user, article_module=2, status=1)
    obj['presentList'] = pictureList
    questionList = SharingModel.objects.filter(article_author=user, article_module=3, status=1)
    obj['thinkingList'] = questionList

if __name__ == '__main__':
    pass
